package com.photoeditor.demo.model.face.report.reportlogic;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.photoeditor.R;
import com.photoeditor.demo.model.bean.TemplateBean;
import com.photoeditor.demo.model.event.GotoAdVideoPageEvent;
import com.photoeditor.demo.model.event.GotoSubscribePageEvent;
import com.photoeditor.demo.model.event.VipMaskIsShowEvent;
import com.photoeditor.demo.model.face.SimpleImageAdapter;
import com.photoeditor.demo.model.face.TopSmoothScroller;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.ui.activity.face.FaceLogicActivity;
import com.photoeditor.demo.util.APKAssertImageLoader;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.face.FaceConstant;
import com.photoeditor.demo.model.bean.face.FaceDetectBeanV4;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.BlurUtil;
import com.photoeditor.demo.util.FastBlur;
import com.photoeditor.demo.util.NetworkUtils;
import com.photoeditor.demo.util.TimeConstant;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.face.FaceBaseCallback;
import com.photoeditor.demo.util.face.FaceUtil;
import com.photoeditor.demo.util.transformation.BlurTransformation;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;

import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_GENDER_SWITCH;
import static com.photoeditor.demo.model.preference.SpUtils.EFFECT_NAME;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;
import static com.photoeditor.demo.util.measureTextViewSizeUtils.measureTextViewSize;

/**
 * Created by @author winn on 2018/10/30.
 */

public class GenderSwitchReportLogic extends BaseReportLogic {

    private final String TAG = GenderSwitchReportLogic.class.getSimpleName();

    private FaceDetectBeanV4 mResultBean;
    private ImageView mImgResult;
    private LottieAnimationView mLoadingView;

    private Context mContext;

    private View mGenderSwitchView;
    private View mContainerView;
    private View mMaskLayout;
    private View mSwitchImageView;
//    private RecyclerView mRvResult;
//    private RecyclerView mRvOther;
//    private SimpleImageAdapter mResultAdapter;
//    private SimpleImageAdapter mOtherAdapter;
    private RecyclerView mRv;
    private SimpleImageAdapter mAdapter;
    private TextView mTvResult;
    private TextView mTvOther;

    private boolean mIsLoading;
    private String mImagePath;
    private String mCompressPic;
    private String mResultBase64;
    private String mCurrentPath;
    private Bitmap mOriBitmap;
    private Bitmap mBluredUserBitmap;
    private Bitmap mBluredScreenBitmap;
    private Map<String, String> mBase64CachedMap;
    private final String TEMPLATE_NO_ID = "no_id";
    private String mCurrentTemplateId;
    private int mLocation = 0;

    private Activity mActivity;

    private boolean mIsModel;

    private String mUsedTemplateId;

    private TopSmoothScroller mTopScroller;

    private int currentPosition = 0;
    private String originalId;

    public GenderSwitchReportLogic(String imagePath) {
        super(REPORT_TYPE_GENDER_SWITCH);
        mImagePath = imagePath;
        mBase64CachedMap = new HashMap<>();
        originalId = TEMPLATE_NO_ID;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
        mTopScroller = new TopSmoothScroller(mActivity);
    }

    @Override
    public View getReportView(ViewGroup parent) {
        mContext = parent.getContext();
        ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.report_gender_switch_new, parent, false);
        initView(viewGroup);

        updateViewIfNecessary();
        return viewGroup;
    }

    private void initView(View rootView) {
        mContentView = rootView;
        mImgResult = rootView.findViewById(R.id.iv_effect);
        mLoadingView = rootView.findViewById(R.id.loading_animation_view);
        mGenderSwitchView = rootView.findViewById(R.id.layout_gender_switch);
        mContainerView = rootView.findViewById(R.id.pic_container);
        mSwitchImageView = rootView.findViewById(R.id.switch_image);
        mRv = rootView.findViewById(R.id.rv);
        mTvResult = rootView.findViewById(R.id.tv_result);
        mTvOther = rootView.findViewById(R.id.tv_other);
        mSwitchImageView.setOnClickListener(this);
        mTvResult.setOnClickListener(this);
        mTvOther.setOnClickListener(this);
        mTvOther.setVisibility(View.INVISIBLE);//加载成功再显示

        mAdapter = new SimpleImageAdapter(this);
        mAdapter.setOnItemClickListener(new SimpleImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, SimpleImageAdapter.SimpleAdapterData data, int postion) {
                currentPosition = postion;
                if (postion > 0) {
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.STATISTIC_EVENT_PIC_CLICK, StatisticsConstant.STATISTIC_KEY_FACE_FUN, StatisticsConstant.STATISTIC_VALUE_GENDER);
                    // TODO: 2/6/20 请求融合接口
                    boolean isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isTemplateUnlocked(data.templateId);
                    OneTimeVipHelper.getInstance().setTemplateId(data.templateId);
                    if (!AppVipManager.isVip() && !mIsModel && !isCurrentAgeUnlocked) {
                        if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                            ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
                        }
                        return;
                    }
                    if (mMaskLayout != null) {
                        mMaskLayout.setVisibility(View.GONE);
                    }
                    if (!isLoading()) {
                        compressAndRequest(data.templateId);
                    }
                } else {
                    if (originalId.equals(TEMPLATE_NO_ID)) {//如果没融合成功，跳转到订阅页
                        boolean isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isTemplateUnlocked(originalId);
                        if (!AppVipManager.isVip() && !mIsModel && !isCurrentAgeUnlocked) {
                            if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                                ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
                            }
                            return;
                        }
                    }
                    if (!isLoading()) {
                        compressAndRequest(/*TEMPLATE_NO_ID*/originalId);
                    }
                }
            }
        });

        setDefaultDataForAdapter();
        mRv.setAdapter(mAdapter);
        mRv.setLayoutManager(new LinearLayoutManager(rootView.getContext(), LinearLayoutManager.HORIZONTAL, false));
        mRv.setItemViewCacheSize(1);

        setTextViewSelected(mTvResult, true);
        setTextViewSelected(mTvOther, false);
    }

    private void setDefaultDataForAdapter() {
        SimpleImageAdapter.SimpleAdapterData data = new SimpleImageAdapter.SimpleAdapterData();
        data.imagePath = mImagePath;
        data.selected = 1;
        data.isVip = 1;//原图设为vip
        mAdapter.addData(data);
        mAdapter.notifyDataSetChanged();
    }

    private void updateDefaultDataForAdapter() {
        SimpleImageAdapter.SimpleAdapterData data = mAdapter.getData(0);
        data.imagePath = mImagePath;
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 更新用户头像
     */
    private void updateViewIfNecessary() {
        updateUserView();
        checkVipView();
        checkModelRequest();
    }

    /**
     * model的假loading请求
     * 2s后展示结果
     */
    private void checkModelRequest() {
        if (!mIsModel) {
            return;
        }
        showLoading();
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                hideLoading();
                setDefaultModelView();
                if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                    ((FaceLogicActivity) mActivity).fakeScanReqSucc();
                }
            }
        }, 2000);
    }

    private void setDefaultModelView() {
        if (mIsModel) {
            //设置头像
            String path = FaceConstant.getModleGengerFeMale(mImagePath);
            APKAssertImageLoader.with(mContext.getResources()).load(path).into(mImgResult);
            
            updateSexIdentityView();
        }
    }

    /**
     * 重置和用户图像相关的数据
     */
    private void resetData() {
        mIsModel = false;
        mResultBean = null;
        mResultBase64 = null;        //请求结果
        mCompressPic = null;         //缓存

        mBluredUserBitmap = null;
        mBluredScreenBitmap = null;
    }

    @Override
    public void updateImage(String image) {
        if (TextUtils.equals(mImagePath, image)) {
            return;
        }
        mImagePath = image;
        if (FaceConstant.isModel(mImagePath)) {
            if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).fakeScanReq();
            }
        }
        resetData();
        updateViewIfNecessary();
        updateDefaultDataForAdapter();
    }

    /**
     * 更新用户头像
     */
    private void updateUserView() {
        mIsModel = FaceConstant.isModel(mImagePath);

        if (mIsModel) {
            mOriBitmap = APKAssertImageLoader.with(mContext.getResources()).load(mImagePath).get();
        } else {
            mOriBitmap = BitmapFactory.decodeFile(mImagePath);
            if (mOriBitmap != null && FaceLogicActivity.degree != 0){  //旋转
                Matrix m = new Matrix();
                m.setRotate(FaceLogicActivity.degree, (float) mOriBitmap.getWidth() / 2, (float) mOriBitmap.getHeight() / 2);
                try {
                    mOriBitmap = Bitmap.createBitmap(mOriBitmap, 0, 0, mOriBitmap.getWidth(), mOriBitmap.getHeight(), m, true);
                } catch (OutOfMemoryError ex) {
                    //
                }
            }
        }
        mCurrentPath = mImagePath;

        mImgResult.setImageBitmap(mOriBitmap);
    }

    public void setResultBean(FaceDetectBeanV4 resultBean) {
        mResultBean = resultBean;
        updateSexIdentityView();
        requestTemplates();
    }

    public void updateSexIdentityView() {
        updateState(!isMale());
    }

    private void updateState(boolean isMale) {
        selectMaleView(isMale);
        if (mIsModel) {
            String modleGenger;
            if (isMale) {
                modleGenger = FaceConstant.getModleGengerMale(mImagePath);
            } else {
                modleGenger = FaceConstant.getModleGengerFeMale(mImagePath);
            }
            if (TextUtils.equals(modleGenger, mImagePath)) {//同性
                mImgResult.setImageBitmap(mOriBitmap);
                mCurrentPath = mImagePath;
            } else {
                mResultBase64 = modleGenger;
                APKAssertImageLoader.with(mContext.getResources()).load(modleGenger).into(mImgResult);
                mCurrentPath = mResultBase64;
            }
        } else if (AppVipManager.isVip()) {
            if (!TextUtils.isEmpty(mResultBase64)) {
                if (mResultBase64.equals(mCurrentPath)) {
                    return;
                }
                showSwapPic(mResultBase64);
                return;
            }
            mImgResult.setImageBitmap(mOriBitmap);
            mCurrentPath = mImagePath;
            compressAndRequest(TEMPLATE_NO_ID);
        } else {
            checkVipView();
        }
    }

    public void doRequest(String templateId) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (mMaskLayout != null) {
                    mMaskLayout.setVisibility(View.GONE);
                }
                if (mOriBitmap != null) {
                    mImgResult.setImageBitmap(mOriBitmap);
                }
            }
        }, 100);
        compressAndRequest(templateId);
    }

    private boolean isMale() {
        if (mIsModel) {
            return !FaceConstant.isFemaleModel(mImagePath);
        } else if (mResultBean == null) {
            return false;
        } else {
            return TextUtils.equals(mResultBean.getGender().toLowerCase(), "male");
        }
    }

    private void selectMaleView(boolean isMale) {

    }

    @Override
    public void onClick(View view) {
        if (isLoading()) {
            return;
        }
        int id = view.getId();
        switch (id) {
            case R.id.switch_image:
                if (mOnEventListener != null) {
                    mOnEventListener.switchImage();
                }
                break;
            case R.id.tv_result:
                setTextViewSelected(mTvResult, true);
                setTextViewSelected(mTvOther, false);
                mLocation = 0;
                mTopScroller.setTargetPosition(0);
                mRv.getLayoutManager().startSmoothScroll(mTopScroller);
                break;
            case R.id.tv_other:
                setTextViewSelected(mTvOther, true);
                setTextViewSelected(mTvResult, false);
                mLocation = 1;
                mTopScroller.setTargetPosition(1);
                mRv.getLayoutManager().startSmoothScroll(mTopScroller);
                break;
            default:
                super.onClick(view);
        }
    }

    public int getLocation() {
        if (TextUtils.equals(mCurrentTemplateId, TEMPLATE_NO_ID)) {
            return 0;
        } else {
            return 1;
        }
    }

    private void setTextViewSelected(TextView textView, boolean selected) {
        if (selected) {
            textView.setTextColor(Color.parseColor("#9478FF"));
        } else {
            textView.setTextColor(Color.parseColor("#5E5D5D"));
        }
    }

    @Override
    public void onSubscribeSuccess() {
//        mMaleView.updateVip(true);
//        mFemaleView.updateVip(true);
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (mMaskLayout != null) {
                    mMaskLayout.setVisibility(View.GONE);
                }
            }
        }, 1000);
        mMaskLayout.setVisibility(View.GONE);
        if (mAdapter != null) {
            ThreadPool.runUITask(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
        updateSexIdentityView();
    }

    private void checkVipView() {
//        SpUtils.obtain().save("gender", mMaleView.isSelected());
        if (AppVipManager.isVip() || mIsModel) {
            if (mMaskLayout != null) {
                mMaskLayout.setVisibility(View.INVISIBLE);
            }
            return;
        }
        //非vip用户弹出遮罩
        if (mMaskLayout != null) {
            createBluredUserBitmap(mOriBitmap);                 //生成用户模糊图片
            mImgResult.setImageBitmap(mBluredUserBitmap);       //设置用户模糊图片
            ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                @Override
                public void run() {
                    createBluredScreenBitmap();
                    if (mBluredScreenBitmap != null) {
//                        mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                        BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                    }
                }
            }, 100);
            mMaskLayout.setVisibility(View.VISIBLE);
            return;
        }
        ViewStub maskStub = (ViewStub) mContentView.findViewById(R.id.stub_subscribe_mask);
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_SHOW,
                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_GENDER_SWAP,
                StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
        mMaskLayout = maskStub.inflate();
        AppCompatTextView textView=mMaskLayout.findViewById(R.id.btn_vip_confirm);
        measureTextViewSize(mActivity,textView,200);
        createBluredUserBitmap(mOriBitmap);             //生成用户模糊图片
        mImgResult.setImageBitmap(mBluredUserBitmap);   //设置用户模糊图片
        ThreadPool.runUITask(new Runnable() {           //设置全屏非Vip遮罩
            @Override
            public void run() {
                createBluredScreenBitmap();
                if (mBluredScreenBitmap != null) {
//                    mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                    BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                }
            }
        }, 100);

        if ((SPDataManager.getTodayHasShowedNorStickersSubscribeMaskCount() < 3)) {
            DLog.d("wLog", "前2次显示模糊页，则页面上不显示激励视频按钮，" +
                    "并在进入模糊页后自动跳转到主订阅页，从主订阅页返回到模糊页，并显示激励视频解锁按钮");
            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
            lps.bottomMargin = DeviceUtils.dip2px(24);
            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
        }
        //策略平台控制，0——旧样式，1——AD弹框，2——评分引导一天免费弹框
//        RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//        boolean value = SPDataManager.getTodayHasShowedAllSubscribeMaskCount() == 2;
//        if (value) {
//            DLog.d("wLog", "第二次进入模糊页，隐藏watch ad按钮");
//        } else {
//            DLog.d("wLog", "非第二次进入模糊页，应该展示watch ad按钮");
//        }
//        if (value || SPDataManager.isFirstCloseSubsPage() || ((beanConfig == null || beanConfig.getRateType() != ADVANCE_OBTAIN_RESULT))) {
//            //模糊页不展示watch video按钮
//            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//            lps.bottomMargin = DeviceUtils.dip2px(24);
//            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
//        }
        mMaskLayout.findViewById(R.id.rl_continue_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_BUTT_CLICK,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_GENDER_SWAP,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
                //跳转到订阅页面
                EventBus.getDefault().post(new GotoSubscribePageEvent());
            }
        });
        mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到激励视频
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_GENDER_SWAP,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
                SpUtils.obtain().save(EFFECT_NAME, "gender");
                EventBus.getDefault().post(new GotoAdVideoPageEvent());
            }
        });

        if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE){
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                    StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                    StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP,
                    StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
        }

        if (mMaskLayout.getVisibility() == View.VISIBLE) {
            ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                @Override
                public void run() {
                    EventBus.getDefault().post(new VipMaskIsShowEvent());
                }
            }, 1000);
        }

    }

//    public boolean getMaleOrFemale(){
//        return mMaleView.isSelected();
//    }

    private void createBluredScreenBitmap() {
        if (mMaskLayout != null) {
            View activityView = mContainerView;
            activityView.setDrawingCacheEnabled(true);
            activityView.destroyDrawingCache();
            activityView.buildDrawingCache();
            Bitmap bmp = activityView.getDrawingCache();
            if (bmp != null) {
                Bitmap copy = bmp.copy(Bitmap.Config.ARGB_8888, true);
                BlurUtil.blur(ComponentContext.getContext(), copy, 10);
                BlurUtil.drawDarkCover(copy);
                mBluredScreenBitmap = copy;
            }
            activityView.destroyDrawingCache();
            activityView.setDrawingCacheEnabled(false);
        }
    }

    private void createBluredUserBitmap(Bitmap srcBitmap) {
        int scaleRatio = 5;
        if (srcBitmap == null || srcBitmap.isRecycled()) {
            return;
        }
        Bitmap blurBitmap = srcBitmap.createScaledBitmap(srcBitmap,
                srcBitmap.getWidth() / scaleRatio,
                srcBitmap.getHeight() / scaleRatio,
                false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blurBitmap = BlurTransformation.blur(ComponentContext.getContext(), blurBitmap, 5);
        } else {
            blurBitmap = FastBlur.doBlur(blurBitmap, 5, true);
        }
        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBluredUserBitmap = Bitmap.createBitmap(blurBitmap.getWidth(), blurBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(mBluredUserBitmap);
        canvas1.drawBitmap(blurBitmap, 0, 0, bitmapPaint);
    }

    /**
     * 首次订阅页返回时调用
     */
    public void updateMaskLayout() {
        if (AppVipManager.isVip()) {
            return;
        }
        if (mMaskLayout != null) {
            checkVipView();
            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
            lps.bottomMargin = DeviceUtils.dip2px(0);
            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
            if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE){
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
            }
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
//                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
//                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
//            RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//            boolean value = SPDataManager.getTodayHasShowedAllSubscribeMaskCount() != 2;
//            if (value) {
//                DLog.d("wLog", "非第二次进入模糊页，应该展示watch ad按钮, extra: " + ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)));
//            } else {
//                DLog.d("wLog", "非第二次进入模糊页，不应该显示watch ad按钮, extra: " + ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)));
//            }
//            if (value && (beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)) {
//                RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//                lps.bottomMargin = DeviceUtils.dip2px(0);
//                mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//                mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
////                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
////                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
////                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);

        }
    }

    private void startRequest() {
        mIsLoading = true;
    }

    private void stopRequest() {
        mIsLoading = false;
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    /**
     * 获取接口请求的耗时区间
     *
     * @param startRequest 开始请求时间
     * @return 区间文本
     */
    private String getTimeInterval(long startRequest) {
        long successRequest = System.currentTimeMillis();
        long diff = successRequest - startRequest;
        float second = diff / 1000f;
        String secondText = "";
        if (second < 4) {
            secondText = "[0.4)";
        } else if (second >= 4 && second < 6) {
            secondText = "[4.6)";
        } else if (second >= 6 && second < 10) {
            secondText = "[6.10)";
        } else if (second >= 10) {
            secondText = "[10.)";
        }
        return secondText;
    }

    /**
     * 换脸接口成功，统计耗时区间
     *
     * @param second 耗时区间
     */
    private void requestSucceedStat(String second) {
//        StatisticsUtils.statisicsCustomFunction(UMENG_CUSTOM_EVENT_EDITOR, UMENG_CUSTOM_KEY_FUNCTION,
//                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_MAINPAGE +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.MAIN_BTN_SWAP +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.FACE_SWAP_REQUEST_SUCCESS +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        second
//        );
    }

    private void requestTemplates() {
        FaceUtil.requestGenderSwitchTemplates(mResultBean.getGender().toLowerCase(), mResultBean.getEthnicity().toLowerCase(), this, new FaceBaseCallback() {
            @Override
            public void onSuccess(Response response) {
                okhttp3.Response rawResponse = response.getRawResponse();
                if (rawResponse == null) {
                    hideLoading();
//                    tryGetTemplatesAgain();
                    return;
                }
                ResponseBody responseBody = rawResponse.body();
                if (responseBody == null) {
                    hideLoading();
//                    tryGetTemplatesAgain();
                    return;
                }
                new ParseTemplateBodyTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, responseBody);
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
            }
        });
    }

    public String getCurrentTemplateId() {
        return mCurrentTemplateId;
    }

    /**
     * 压缩图片，请求接口
     */
    private void compressAndRequest(String templateId) {
        mCurrentTemplateId = templateId;
        if (currentPosition == 0 && originalId.equals(TEMPLATE_NO_ID)) {
            originalId = mCurrentTemplateId;
        }
        String cachedBitmapBase64 = mBase64CachedMap.get(templateId);
        if (!TextUtils.isEmpty(cachedBitmapBase64)) {
            showSwapPic(cachedBitmapBase64);
            return;
        }

//        if (!TextUtils.isEmpty(mResultBase64)) {
//            showSwapPic(mResultBase64);
//            return;
//        }
        showLoading();
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                if (mResultBean == null) {
                    if (mOnEventListener != null) {
                        mOnEventListener.updateResultBean();
                    }
                    return;
                }
                //增加压缩缓存，因为原图和模板合并，原图pic是固定，只需要压缩一次，就可以，下次请求可以复用
                if (!TextUtils.isEmpty(mCompressPic)) {
                    requestSwap(mCompressPic, templateId);
                    return;
                }
                //
                Bitmap bitmap = ImageHelper.getBitmapFromPath(mImagePath);
                if (bitmap == null){
                    Toast.makeText(mActivity, "bitmap is empty", Toast.LENGTH_SHORT).show();
                    return;
                }
                //压缩图片
                Bitmap bitmap1 = ImageHelper.compressJpgToLimitKB(bitmap, 100);
                if (bitmap1 == null){
                    Toast.makeText(mActivity, "bitmap is empty", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    mCompressPic = ImageHelper.bitmapToBase64(bitmap1);
                    DLog.i(TAG, "onSuccess: compressImage");
                    requestSwap(mCompressPic, templateId);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private long startRequest;

    private void requestSwap(String pic, String templateId) {
        startRequest = System.currentTimeMillis();
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_GENDER_SWAP);

        DLog.e(TAG, "requestSwap");
        FaceUtil.requestGenderSwitch(pic, templateId, mResultBean.getGender().toLowerCase(), mResultBean.getEthnicity().toLowerCase(), this, new FaceBaseCallback() {
            @Override
            public void onSuccess(Response response) {
                DLog.e(TAG, "requestSwap -> success");
                //network error
                if (!NetworkUtils.isNetworkAvailable(mActivity)){
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_FAIL,
                            StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                            StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_GENDER_SWAP,
                            StatisticsConstant.KEY_RESULT_FAIL_REASON, "network");
                    return;
                }
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_SUCCESS,
                        StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                        StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_GENDER_SWAP,
                        StatisticsConstant.KEY_REQUEST_TIME, getTimeInterval(startRequest));

                okhttp3.Response rawResponse = response.getRawResponse();
                if (rawResponse == null) {
                    hideLoading();
                    tryGetTemplatesAgain();
                    return;
                }
                ResponseBody responseBody = rawResponse.body();
                if (responseBody == null) {
                    hideLoading();
                    tryGetTemplatesAgain();
                    return;
                }
                new ParseBodyTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, responseBody);
            }

            @Override
            public void onError(Response response) {
                hideLoading();
                DLog.e(TAG, "requestSwap -> onError");
                tryGetTemplatesAgain();
                statisFaild();
                ToastUtil.showToast(R.string.gender_swap_failed);
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_FAIL,
                        StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                        StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_GENDER_SWAP,
                        StatisticsConstant.KEY_RESULT_FAIL_REASON, response.message());
            }
        });
    }

    class ParseTemplateBodyTask extends AsyncTask<ResponseBody, Void, List<TemplateBean>> {
        @Override
        protected List<TemplateBean> doInBackground(ResponseBody... responseBodies) {
            if (responseBodies == null || responseBodies.length < 1) {
                return null;
            }
            ResponseBody responseBody = responseBodies[0];
            try {
                String result = responseBody.string();
                if (TextUtils.isEmpty(result)) {
//                    hideLoading();
                    return null;
                }
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.optInt("code");
                if (code == 3) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
//                            hideLoading();
                            ToastUtil.showToast(R.string.concurrency_limit_tip);
                        }
                    });
                    return null;
                }
                if (!jsonObject.optBoolean("success")) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
//                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                String dataString = jsonObject.optString("data");
                if (TextUtils.isEmpty(dataString)) {
                    return null;
                }

                Type type = new TypeToken<List<TemplateBean>>(){}.getType();
                Gson gson = new Gson();
                List<TemplateBean> list = gson.fromJson(dataString, type);
                if (list == null || list.isEmpty()) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
//                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                return list;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            tryGetTemplatesAgain();
            return null;
        }

        @Override
        protected void onPostExecute(List<TemplateBean> templateBeans) {
            if (templateBeans == null || templateBeans.isEmpty()) {
                return;
            }
            List<SimpleImageAdapter.SimpleAdapterData> list = new ArrayList<>();
            int size = templateBeans.size();
            for(int i=0; i<size; i++) {
                TemplateBean bean = templateBeans.get(i);
                SimpleImageAdapter.SimpleAdapterData data = new SimpleImageAdapter.SimpleAdapterData();
                data.imagePath = bean.getThumbnailUrl();
                if (i == 0) {
                    data.isVip = 0;
                    OneTimeVipHelper.getInstance().forceUnlockTemplate(bean.getTemplateId());
                } else {
                    data.isVip = 1;
                }
                data.templateId = bean.getTemplateId();
                list.add(data);
            }
            mAdapter.addDatas(list);
            mAdapter.removeDataByTemplateId(mUsedTemplateId);
            mAdapter.notifyDataSetChanged();
            mTvOther.setVisibility(View.VISIBLE);
        }
    }

    class ParseBodyTask extends AsyncTask<ResponseBody, Void, String> {
        @Override
        protected String doInBackground(ResponseBody... responseBodies) {
            if (responseBodies == null || responseBodies.length < 1) {
                return null;
            }
            ResponseBody responseBody = responseBodies[0];
            try {
                String result = responseBody.string();
                if (TextUtils.isEmpty(result)) {
                    hideLoading();
                    return null;
                }
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.optInt("code");
                if (code == 3) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                            ToastUtil.showToast(R.string.concurrency_limit_tip);
                        }
                    });
                    return null;
                }
                if (!jsonObject.optBoolean("success")) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                JSONObject dataJsonObj = jsonObject.optJSONObject("data");
                if (dataJsonObj == null) {
                    return null;
                }
                mUsedTemplateId = dataJsonObj.optString("templateId");
                if (TextUtils.equals(mCurrentTemplateId, TEMPLATE_NO_ID)) {
                    DLog.d("gLog", "使用的模板id为 " + mCurrentTemplateId + "， 移除模板：" + mUsedTemplateId);
                    mAdapter.removeDataByTemplateId(mUsedTemplateId);
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
                String picBase64 = dataJsonObj.optString("templateBase64Str");
                if (TextUtils.isEmpty(picBase64)) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                //统计
//                requestSucceedStat(getTimeInterval(startRequest));
                DLog.i(TAG, "onSuccess: " + picBase64);
                return picBase64;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            tryGetTemplatesAgain();
            return null;
        }

        @Override
        protected void onPostExecute(String picBase64) {
            super.onPostExecute(picBase64);
            hideLoading();
            mResultBase64 = picBase64;
            if (!TextUtils.isEmpty(mResultBase64)) {
                mBase64CachedMap.put(mCurrentTemplateId, picBase64);
                hideLoading();
                //显示到image view
                showSwapPic(mResultBase64);
            }
        }
    }

    protected String getStatisticsSuccessType() {
        if (startRequest == 0) {
            startRequest = System.currentTimeMillis();
        }
        long durationSec = (System.currentTimeMillis() - startRequest) / TimeConstant.ONE_SEC;
        if (durationSec <= 4 && durationSec >= 0) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
        } else if (durationSec <= 6) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
        } else if (durationSec <= 10) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
        } else {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;
        }
    }

    private void statisFaild() {
        StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_GENDER_SWITCH + "_" +
                StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC_FAIL + "_"
                + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST);
    }

    private void tryGetTemplatesAgain() {
        if (mActivity == null) {
            return;
        }


        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showToast(R.string.gender_swap_failed);
            }
        });
    }

    @Override
    public Bitmap getSaveImg() {
        if (mIsModel) {
            return APKAssertImageLoader.with(mContext.getResources()).load(mCurrentPath).get();
        }
        if (!TextUtils.isEmpty(mCurrentPath)) {
            Bitmap bitmap = BitmapUtils.base64ToBitmap(mCurrentPath);
            if (bitmap == null) {
                bitmap = ImageHelper.getBitmapFromPath(mCurrentPath);
            }
            return bitmap;
        } else {
            return ImageHelper.getBitmapFromPath(mImagePath);
        }
    }

    private void showLoading() {
        DLog.d("lLog", "logic showLoading()");
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
            mLoadingView.playAnimation();
            mIsLoading = true;
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).showEmptyViewCount++;
                ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.VISIBLE);
            }
        }
    }

    private void hideLoading() {
        DLog.d("lLog", "logic hideLoading()");
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
            mLoadingView.cancelAnimation();
            mIsLoading = false;
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).showEmptyViewCount--;
                if (((FaceLogicActivity) mActivity).showEmptyViewCount == 0) {
                    ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 显示最终图片的同时，需要更换模糊背景，更换模糊背景genBackground，直接rx子线程执行。
     *
     * @param pic
     */
    private void showSwapPic(final String pic) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                ImageLoader.loadImageFromBase64(ComponentContext.getContext(), pic, mImgResult);
                mCurrentPath = pic;
            }
        });
    }

    @Override
    public int getReportTitleResId() {
        return R.string.gender_switch;
    }

    @Override
    public String getFeatureType() {
        return StatisticsConstant.STATISTIC_EVENT_FEATURE_VALUE_FEATURE_GENDER_SWITCH;
    }

    @Override
    public boolean needScrool() {
        return true;
    }


    @Override
    public boolean titleBarWithoutBg() {
        return true;
    }

    public void destroy() {
        mActivity = null;
        OkGo.getInstance().cancelTag(this);
    }

}
